<template>
	<view class="meal-container">
		<!-- 搜索栏 -->
		<view class="search-box">
			<input class="search-input" type="text" v-model="keyword" placeholder="请输入申请人姓名"
				@input="onSearchInput" />
		</view>

		<!-- 状态筛选区域 -->
		<view class="status-filter">
			<uni-segmented-control :current="current" :values="items" :style-type="'text'" :active-color="'#2979ff'"
				@clickItem="onClickItem" />
		</view>

		<!-- 列表区域 -->
		<scroll-view scroll-y="true" class="meal-list" @refresherrefresh="onRefresh" :refresher-enabled="true"
			@scrolltolower="loadMore">
			<view v-if="loading && data.length === 0" class="loading">
				<text>加载中...</text>
			</view>

			<view v-if="data.length === 0 && !loading" class="empty-state">
				<image src="/static/avatar/empty.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无{{items[current]}}的送餐任务</text>
			</view>

			<view v-for="(item,index) in data" :key="item._id" class="meal-card" :class="'status-' + item.status">
				<!-- 卡片头部 -->
				<view class="card-header">
					<view class="user-info">
						<image :src="item.avatar || '/static/avatar/avatar.png'" class="user-avatar"></image>
						<view>
							<text class="username">{{ item.username }}</text>
							<text class="mobile">联系电话：{{ item.mobile }}</text>
						</view>
					</view>
					<view class="status-tag" :class="'status-' + item.status">
						{{ statusText[item.status] }}
					</view>
				</view>

				<!-- 用餐信息 -->
				<view class="meal-info">
					<view class="meal-item">
						<uni-icons type="time" size="16" color="#666"></uni-icons>
						<text class="meal-text">用餐时间: {{ item.dinner_time }}</text>
					</view>
					<view class="meal-item">
						<uni-icons type="location" size="16" color="#666"></uni-icons>
						<text class="meal-text">送餐地点: {{ item.location || '未指定' }}</text>
					</view>
					<view class="meal-details">
						<view class="detail-tag" :class="item.type === 1 ? 'box-meal' : 'table-meal'">
							{{ item.type == 1 ? '盒饭' : '桌餐' }}
						</view>
						<view class="detail-tag people-count">
							<uni-icons type="person" size="14" color="#666"></uni-icons>
							{{ item.num }}人
						</view>
					</view>
				</view>

				<!-- 事由 -->
				<view class="reason-box">
					<uni-icons type="compose" size="16" color="#666"></uni-icons>
					<text class="reason-text">{{ item.reason }}</text>
				</view>

				<!-- 操作按钮 -->
				<view class="action-buttons">
					<button class="action-btn view-btn" @click="viewClick(item._id)">
						查看详情
					</button>
					<button v-if="item.status == 1" class="action-btn complete-btn" @click="completeClick(item._id)">
						完成任务
					</button>
				</view>
			</view>

			<!-- 加载更多组件 -->
			<uni-load-more :status="loadingStatus" v-if="data.length > 0" />
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				role: -1,
				userinfo: {},
				keyword: '',
				current: 0,
				page: 1,
				pageSize: 10,
				total: 0,
				loading: false,
				data: [],
				items: ['未完成', '已完成'],
				statusText: {
					1: "进行中",
					2: "已完成"
				},
				searchTimer: null
			}
		},
		computed: {
			loadingStatus() {
				if (this.loading) return 'loading';
				if (this.data.length >= this.total) return 'noMore';
				return 'more';
			}
		},
		onShow() {
			this.resetPagination();
			this.fetchData();
			const userInfo = uni.getStorageSync('userInfo');
			this.role = userInfo.role?.value || 0;
		},
		methods: {
			resetPagination() {
				this.page = 1;
				this.data = [];
				this.total = 0;
			},
			onRefresh() {
				this.resetPagination();
				this.fetchData().finally(() => {
					uni.stopPullDownRefresh();
				});
			},
			onSearchInput() {
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.resetPagination();
					this.fetchData();
				}, 500);
			},
			loadMore() {
				if (!this.loading && this.data.length < this.total) {
					this.page++;
					this.fetchData();
				}
			},
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex;
					this.resetPagination();
					this.fetchData();
				}
			},
			async fetchData() {
				if (this.loading) return;
				this.loading = true;

				try {
					const obj = uniCloud.importObject('schedules');
					const res = await obj.getMealSchedules({
						status: this.current + 1,
						keyword: this.keyword.trim(),
						page: this.page,
						pageSize: this.pageSize
					});

					if (res.code === 0) {
						this.total = res.total || 0;
						const newData = (res.data || []).map(item => ({
							...item,
							status: item.status === 1 ? 1 : 2
						}));

						if (this.page === 1) {
							this.data = newData;
						} else {
							this.data = [...this.data, ...newData];
						}
					} else {
						if (this.page === 1) {
							this.data = [];
							this.total = 0;
						}
					}
				} catch (err) {
					//console.error('请求失败:', err);
					if (this.page === 1) {
						this.data = [];
						this.total = 0;
					}
				} finally {
					this.loading = false;
				}
			},
			completeClick(id) {
				let event = {
					_id: id,
					data: {
						status: 2,
						end_time: uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
					}
				};
				this.updateMealSchedules(event).then(() => {
					this.fetchData();
				});
			},
			viewClick(id) {
				uni.$router.to({
					url: '/pagesA/meal/info',
					params: {
						_id: id
					}
				});
			},
			async updateMealSchedules(e) {
				try {
					const obj = uniCloud.importObject('schedules');
					const res = await obj.updateMealSchedules(e);
					if (res.code === 0) {
						uni.showToast({
							title: '操作成功',
							icon: 'success'
						});
						return true;
					}
				} catch (e) {
					//console.error(e);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
					return false;
				}
			}
		}
	}
</script>

<style lang="scss">
	$primary-color: #2979ff;
	$success-color: #18bc37;
	$box-meal-color: #3498db;
	$table-meal-color: #e74c3c;

	.meal-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f7fa;
		padding: 20rpx;
	}

	.search-box {
		background: #fff;
		padding: 20rpx;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);

		.search-input {
			background: #f5f5f5;
			padding: 15rpx 20rpx;
			border-radius: 8rpx;
			font-size: 28rpx;
		}
	}

	.status-filter {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
	}

	.meal-list {
		flex: 1;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 0;

		.empty-image {
			width: 300rpx;
			height: 300rpx;
			opacity: 0.6;
		}

		.empty-text {
			font-size: 30rpx;
			color: #999;
			margin-top: 30rpx;
		}
	}

	.loading {
		text-align: center;
		padding: 40rpx;
		color: #999;
		font-size: 28rpx;
	}

	.meal-card {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		position: relative;
		overflow: hidden;

		&::before {
			content: "";
			position: absolute;
			left: 0;
			top: 0;
			bottom: 0;
			width: 8rpx;
		}

		&.status-1::before {
			background: #4facfe;
		}

		&.status-2::before {
			background: #43e97b;
		}
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 20rpx;
	}

	.user-info {
		display: flex;
		align-items: center;

		.user-avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			margin-right: 20rpx;
			background: #f0f7ff;
		}

		.username {
			font-size: 32rpx;
			font-weight: bold;
			display: block;
		}

		.mobile {
			font-size: 26rpx;
			color: #666;
		}
	}

	.status-tag {
		padding: 8rpx 20rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
		font-weight: bold;

		&.status-1 {
			background: rgba(79, 172, 254, 0.2);
			color: #4facfe;
		}

		&.status-2 {
			background: rgba(67, 233, 123, 0.2);
			color: #43e97b;
		}
	}

	.meal-info {
		margin-bottom: 20rpx;

		.meal-item {
			display: flex;
			align-items: center;
			padding: 12rpx 0;
			font-size: 28rpx;
			color: #666;

			uni-icons {
				margin-right: 10rpx;
			}
		}
	}

	.meal-details {
		display: flex;
		margin-top: 20rpx;
		gap: 20rpx;

		.detail-tag {
			padding: 6rpx 20rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			display: flex;
			align-items: center;

			&.box-meal {
				background: rgba($box-meal-color, 0.1);
				color: $box-meal-color;
			}

			&.table-meal {
				background: rgba($table-meal-color, 0.1);
				color: $table-meal-color;
			}

			&.people-count {
				background: rgba($primary-color, 0.1);
				color: $primary-color;
			}
		}
	}

	.reason-box {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
		margin: 20rpx 0;
		display: flex;

		.reason-text {
			font-size: 28rpx;
			color: #333;
			margin-left: 10rpx;
			line-height: 1.5;
		}
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;

		.action-btn {
			padding: 0 30rpx;
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			border: none;

			&::after {
				border: none;
			}

			&.view-btn {
				background: #f0f4f8;
				color: $primary-color;
			}

			&.complete-btn {
				background: rgba($success-color, 0.1);
				color: $success-color;
			}
		}
	}
</style>